package com.cloudcc.mobile.view.web;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.SharePreferece;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.db.ApprovalDB;
import com.cloudcc.mobile.db.EventDB;
import com.cloudcc.mobile.db.TaskDB;
import com.cloudcc.mobile.dialog.CallLogLoadingDialog;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.NotificationUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.activity.BindActivity;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.lidroid.xutils.exception.DbException;
import com.litesuits.android.log.Log;

public class NewWebViewActivity extends Activity {
	private String mEns = RunTimeManager.getInstance().getlanguage();

	public static NewWebViewActivity instance = null;
	private WebView webview;
	protected String mUrl = StringUtils.EMPTY;
	// Context mContext;
	private boolean _isVisible;// 控制bindtoken影响的问题
	protected CallLogLoadingDialog mProgress;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		instance = this;
		setContentView(R.layout.newworkwebview);
		mProgress = new CallLogLoadingDialog(this,R.style.DialogLoadingTheme);
		

		try {
			setView();
		} catch (DbException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		webview = (WebView) findViewById(R.id.newworkweb);
		webview.requestFocus();
		webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);// 防止滑动的时候闪屏
		mUrl = AppContext.urlString;
		webview.loadUrl(mUrl);
		webview.reload();

		WebSettings webstting = webview.getSettings();
		webstting.setJavaScriptEnabled(true);
		webstting.setAllowFileAccess(true);
		webstting.setSupportZoom(true);
		webstting.setCacheMode(WebSettings.LOAD_DEFAULT);// 是否缓存
		webstting.setBlockNetworkImage(false);
		webstting.setJavaScriptCanOpenWindowsAutomatically(true);

		webstting.setDomStorageEnabled(true);
		webstting.setDatabaseEnabled(true);
		webstting.setDatabasePath(this.getApplicationContext().getCacheDir()
				.getAbsolutePath());
		setListener();
	}
	private TaskDB db3;
	private ApprovalDB db4;
	private EventDB db5;
	private SharePreferece share;
	private NetWork net;
	private void setView() throws DbException {
		db3 = new TaskDB(NewWebViewActivity.this, UserManager.getManager().getUser().userId
				+ "chat");
		db4 = new ApprovalDB(NewWebViewActivity.this,
				UserManager.getManager().getUser().userId + "chat");
		db5 = new EventDB(NewWebViewActivity.this, UserManager.getManager().getUser().userId
				+ "chat");
		
		
		share = new SharePreferece(NewWebViewActivity.this);
		net = new NetWork();
		String action = getIntent().getStringExtra("MyPushMessageReceiver");
		if (action != null && !action.trim().equals("")
				&& !action.trim().equals("null")) {
			if (action.equals("task")) {
				NotificationUtils.clearNotification(NewWebViewActivity.this, 2001);
				db3.deleteTaskAll();
				AppContext.urlString = UrlTools.weixinUrl + UrlTools.TaskUrl;
				Intent intent = new Intent(AppContext.TASK_NUM);
				sendBroadcast(intent);
			} else if (action.equals("approval")) {
				NotificationUtils.clearNotification(NewWebViewActivity.this, 2002);
				db4.deleteApprovalAll();
				AppContext.urlString = UrlTools.weixinUrl
						+ UrlTools.ApprovalUrl;
				Intent intent = new Intent(AppContext.DAISHENPI_NUM);
				sendBroadcast(intent);
			} else if (action.equals("event")) {
				NotificationUtils.clearNotification(NewWebViewActivity.this, 2003);
				db5.deleteEventAll();
				AppContext.urlString = UrlTools.weixinUrl + UrlTools.EventUrl;
				Intent intent = new Intent(AppContext.EVENT_NUM);
				sendBroadcast(intent);
			}
		} else {

		}
		
	}

	@Override
	protected void onPause() {
		_isVisible = false;

		super.onPause();
	}

	@Override
	protected void onResume() {
		_isVisible = true;
		super.onResume();
	}

	protected void showProgress() {
		if (_isVisible) {
			if (mProgress == null) {
				mProgress = new CallLogLoadingDialog(this,R.style.DialogLoadingTheme);
				mProgress.show();
				mProgress.settext(getString(R.string.loading));
			}
			if (mProgress != null) {
				mProgress.setCancelable(true);
				mProgress.setCanceledOnTouchOutside(false);
				mProgress.show();
			}
		}
	}

	/**
	 * 停止进度条
	 */
	protected void stopProgress() {
		if (_isVisible && mProgress != null) {
			try {
				mProgress.dismiss();
				mProgress = null;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	private void setListener() {
		Log.d("webview", "webview" + mUrl);
		
		webview.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {

				LogUtils.d("webview", "开始加载url" + url);
				showProgress();
				if (url.equals(AppContext.indexUrl)) {
					NewWebViewActivity.this.finish();

					return;
				}
				if (url.equals(UrlTools.loginurl)) {
					Intent intent = new Intent(UrlTools.loginurl);
					NewWebViewActivity.this.sendBroadcast(intent);
				}
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				LogUtils.d("webview", "加载完成url" + url);

				AppContext.isFirst = true;
				webview.setVisibility(View.VISIBLE);
				stopProgress();
				super.onPageFinished(view, url);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if (UrlManager.isWapLogin(url)) {// 跳转去登录
					EventEngine.register(NewWebViewActivity.this);
					Intent intent = new Intent(NewWebViewActivity.this, BindActivity.class);
					startActivity(intent);
					return true;
				}
				if (url.equals(UrlTools.weixinUrl + UrlTools.wxIndexUrl)) {
					NewWebViewActivity.this.finish();
					return true;
				} else if (StringUtils.contains(url, "/wx_taskquery.action?m=query&id=")) {


					String id = url.substring(
							Tools.getCharacterPosition(url, "=", 2) + 1,
							Tools.getCharacterPosition(url, "&", 2));
					Intent intent = new Intent(NewWebViewActivity.this, BeauInfoActivity.class);
					intent.putExtra("web", id);
					if((id.startsWith("bef"))){//事件
						intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl_z(id));
						intent.putExtra("from", "webview");
					}else if((id.startsWith("bfa"))){//任务
						intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl_z(id));
						intent.putExtra("matters", "matter");
					}else{
						intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl(id));

					}	
					startActivity(intent);

					return true;
				}else if(StringUtils.contains(url, "wx_taskquery.action?id")){
					String id = url.substring(
							Tools.getCharacterPosition(url, "id=", 1) + 3,
							Tools.getCharacterPosition(url, "&", 1));
					Intent intent = new Intent(NewWebViewActivity.this, BeauInfoActivity.class);
					intent.putExtra("web", id);
					
					if((id.startsWith("bef"))){//事件
						intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl_z(id));
						intent.putExtra("from", "webview");
					}else if((id.startsWith("bfa"))){//任务
						intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl_z(id));
						intent.putExtra("matters", "matter");
					}else{
						intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl(id));

					}		
					startActivity(intent);
					NewWebViewActivity.this.finish();
					return true;
				} else {
					// 自身加载新链接,不做外部跳转
					view.loadUrl(url);
					return true;
				}
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				AppContext.isError = true;
				
//				if ("en".equals(mEns)) {
//					view.loadUrl("file:///android_asset/html/en_error.html");
//				}else{
					view.loadUrl("file:///android_asset/html/error.html");
//			}
			}
		});
	}

}
